import {Component, NgZone, OnInit} from '@angular/core';
import {animate, state, style, transition, trigger} from '@angular/animations';
import {ConsulService} from './service/consul.service';
import {ElectronService} from 'ngx-electron';
import {ConfigService} from './service/config.service';
import {MatDialog} from '@angular/material/dialog';
import {DeregisterDialogComponent} from './component/deregister-dialog/deregister-dialog.component';
import {Future} from './util/future';
import {ServiceEntity} from './model/service-entity';
import {map} from 'rxjs/operators';
import {MatTableDataSource} from '@angular/material/table';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({height: '0px', minHeight: '0'})),
      state('expanded', style({height: '*'})),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
    ]),
  ],
})
export class AppComponent implements OnInit {
  displayedColumns: string[] = ['index', 'id', 'address', 'state', 'op'];
  dataSource = new MatTableDataSource<ServiceEntity>();

  constructor(public dialog: MatDialog, public config: ConfigService, private consulService: ConsulService) {
    this.config.host = '192.168.0.103';
    this.config.port = 8500;
  }

  ngOnInit(): void {
    /*this.electron.ipcRenderer.on('main-log-channel', (event, name, ...args) => {
      console.log('main', name, args);
    });*/

    this.refresh();
  }

  public refresh(healthCheck: boolean = true) {
    if (this.dataSource.data) {
      this.dataSource.data.forEach(v => {
        v.healthCheck.cancel();
      });
    }

    let obs = this.consulService.getService();
    obs = healthCheck ? obs.pipe(map(value => this.healthCheck(value))) : obs;
    obs.subscribe(value => {
      this.dataSource.data = value;
    });
  }

  private healthCheck(services: ServiceEntity[]): ServiceEntity[] {
    for (const service of services) {
      const address = `${service.Address}:${service.Port}`;
      service.healthCheck = new Future<string>(this.consulService.healthCheck(address));
    }
    return services;
  }

  public confirmDeregister(serviceId: any) {
    const dialogRef = this.dialog.open(DeregisterDialogComponent, {
      width: '450px',
      data: serviceId,
      disableClose: true,
    });
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.consulService.deregister(serviceId).subscribe(() => {
          if (this.dataSource.data) {
            this.dataSource.data = this.dataSource.data.filter(v => v.ID !== serviceId);
          }
        });
      }
    });
  }

  log(element: any) {
    console.log(element);
  }

  settings() {

  }

  public trackBy(index, item: ServiceEntity) {
    return item.ID;
  }
}
